import { createComplugin, utils } from 'complugin'
import { transform } from 'sucrase'

type SucraseOptions = Omit<Partial<import('sucrase').Options>, 'fileName' | 'minify' | 'include' | 'exclude'>

declare namespace compluginSucrase {
  interface Options extends SucraseOptions {
    include?: (string | RegExp)[]
    exclude?: (string | RegExp)[]
  }
}

const compluginSucrase = createComplugin<compluginSucrase.Options>({
  name: 'sucrase',
  enforce: undefined,
  factory(options, meta) {
    const { include: _include = [/\.(tsx?|jsx?|mjs)$/i], exclude: _exclude, ..._sucraseOptions } = options ?? {}
    const sucraseOptions: import('sucrase').Options = {
      disableESTransforms: true,
      ..._sucraseOptions,
      transforms: _sucraseOptions.transforms ?? ['typescript']
    }

    return {
      transformInclude: utils.createFilter(_include, _exclude),
      transform(code, id) {
        const result = transform(code, sucraseOptions)
        return {
          code: result.code,
          map: result.sourceMap as any
        }
      }
    }
  }
})

// @ts-ignore
compluginSucrase.default = compluginSucrase

export = compluginSucrase
